<template>
    <div class="p-4 flex flex-col h-full">
        <div class="flex items-center min-h-[42px] mb-5">
            <icon
                name="svg-icon-Back"
                size="26"
                class="cursor-pointer"
                @click="emits('toRow', 'archive')"
            />
            <div class="ml-3">
                <h3 class="text-lg font-medium">{{ archive.name }}</h3>
                <p class="text-xs text-tx-placeholder">文档编号: {{ archive.code }}</p>
            </div>
        </div>

        <div class="flex items-center justify-between mb-4">
            <div class="flex items-center">
                <el-button
                    class="h-[38px]"
                    type="primary"
                    :disabled="know.power < permissionEnum.EDIT"
                    @click="handleCorrect('')"
                >插入数据</el-button>
                <el-button
                    class="h-[38px]"
                    :icon="Refresh"
                    @click="resetPaging"
                >刷新</el-button>
                <el-button
                    class="h-[38px]"
                    :disabled="!tableRef?.getSelectionRows().length || know.power < permissionEnum.EDIT"
                    @click="batchRetry"
                >批量重试</el-button>
                <el-button
                    class="h-[38px]"
                    :disabled="!tableRef?.getSelectionRows().length || know.power < permissionEnum.EDIT"
                    @click="batchDelete"
                >批量删除</el-button>
            </div>
            <div class="flex items-center">
                <div class="w-[220px] ml-2">
                    <el-input
                        v-model="queryParams.keyword"
                        size="large"
                        placeholder="搜索关键词"
                        :prefix-icon="Search"
                        clearable
                        @keyup.enter="resetPaging"
                    />
                </div>
                <div class="w-[160px] ml-2">
                    <el-select
                        v-model="queryParams.status"
                        placeholder="学习状态"
                        clearable
                    >
                        <el-option label="全部" value=""/>
                        <el-option label="等待中" value="0"/>
                        <el-option label="排队中" value="1"/>
                        <el-option label="学习中" value="2"/>
                        <el-option label="学习成功" value="3"/>
                        <el-option label="学习失败" value="4"/>
                    </el-select>
                </div>
                <el-button
                    class="ml-3 h-9"
                    type="primary"
                    :icon="Search"
                    @click="resetPaging"
                >搜索</el-button>
            </div>
        </div>

        <el-table
            ref="tableRef"
            v-loading="pager.loading"
            :data="pager.lists"
            size="large"
            style="height: 100%"
            row-class-name="h-[70px]"
        >
            <el-table-column type="selection" width="40" />
            <el-table-column label="文档内容" prop="question" min-width="200">
                <template #default="scope: { row: KnowDatasetListResponse }">
                    <p class="line-clamp-3">{{ scope.row.question }}</p>
                </template>
            </el-table-column>
            <el-table-column label="补充内容" prop="answer" min-width="200">
                <template #default="scope: { row: KnowDatasetListResponse }">
                    <p class="line-clamp-3">{{ scope.row.answer || '-' }}</p>
                </template>
            </el-table-column>
            <el-table-column label="字符数量" prop="character" min-width="100" />
            <el-table-column label="消耗积分" prop="use_points" min-width="100" />
            <el-table-column label="学习状态" prop="answer" min-width="100">
                <template #default="scope: { row: KnowDatasetListResponse }">
                    <el-tag v-if="scope.row.status === 0" type="info">等待中</el-tag>
                    <el-tag v-if="scope.row.status === 1" type="info">排队中</el-tag>
                    <el-tag v-if="scope.row.status === 2" type="warning">学习中</el-tag>
                    <el-tag v-if="scope.row.status === 3" type="success">学习成功</el-tag>
                    <el-tag v-if="scope.row.status === 4" type="danger" class="cursor-pointer">
                        <popup title="失败原因" cancelButtonText="" confirmButtonText="">
                            <template #trigger>学习失败</template>
                            <div class="text-error p-2">{{ scope.row.error }}</div>
                        </popup>
                    </el-tag>
                    <p
                        v-if="scope.row.error"
                        class="mt-0.5 text-xs text-error line-clamp-3"
                    >
                        原因: {{ scope.row.error }}
                    </p>
                </template>
            </el-table-column>
            <el-table-column label="创建/更新时间" min-width="120" >
                <template #default="scope: { row: KnowDatasetListResponse }">
                    <p>{{ scope.row.create_time }}</p>
                    <p>{{ scope.row.update_time }}</p>
                </template>
            </el-table-column>
            <el-table-column min-width="50" >
                <template #default="scope: { row: KnowDatasetListResponse }">
                    <el-dropdown>
                        <icon name="el-icon-MoreFilled" color="#999" />
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="handleCorrect(scope.row.id)">
                                    <div class="flex items-center py-[2px]">
                                        <icon name="el-icon-Edit"/>
                                        <span class="ml-1">修正数据</span>
                                    </div>
                                </el-dropdown-item>
                                <el-dropdown-item v-if="scope.row.status === 4" divided>
                                    <div class="flex items-center py-[2px]" @click="handleRetry([scope.row.id])">
                                        <icon name="el-icon-Refresh" />
                                        <span class="ml-1">重新训练</span>
                                    </div>
                                </el-dropdown-item>
                                <el-dropdown-item divided @click="handleDelete([scope.row.id])" >
                                    <div class="flex items-center py-[2px]">
                                        <icon name="el-icon-Delete" />
                                        <span class="ml-1">删除数据</span>
                                    </div>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <div class="flex justify-end pt-4">
            <paging
                v-if="pager.lists.length > 0"
                v-model="pager"
                layout="total, sizes, prev, pager, next, jumper"
                @change="queryLists"
            />
        </div>

        <popup-know-amend
            :show="editShow"
            :loading="loading"
            :async-close="true"
            :uuid="editUuid"
            @close="editShow = false"
            @confirm="handleUpdate"
        />
    </div>
</template>

<script setup lang="ts">
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElTable } from 'element-plus'
import { permissionEnum } from '~/enums/app'
import knowArchiveApi from '~/api/agent/know/archive'
import knowDatasetApi from '~/api/agent/know/dataset'
import PopupKnowAmend from '../../_components/popup-know-amend.vue'

const emits = defineEmits(['toRow'])
const props = withDefaults(
    defineProps<{
        know: KnowManageDetailResponse;
        archiveId: string;
    }>(),
    {}
)

// 表格引用
const tableRef = ref<InstanceType<typeof ElTable>>()

// 编辑数据
const loading = ref<boolean>(false)
const editShow = ref<boolean>(false)
const editUuid = ref<string>('')
const archive = ref<any>({} as KnowArchiveDetailResponse)

// 查询参数
const queryParams = reactive({
    archive_id: props.archiveId,
    status: '',
    keyword: ''
})

// 分页查询
const {
    pager,
    queryLists,
    resetPaging
} = usePaging({
    fetchFun: knowDatasetApi.lists,
    params: queryParams
})

/**
 * 检测训练数据
 */
const checkWaitingData = async () => {
    const uuids: string[] = []
    pager.lists.forEach(item => {
        if ([0, 1, 2].includes(item.status)) {
            uuids.push(String(item.id))
        }
    })

    if (uuids.length === 0) {
        end()
    } else {
        const lists = await knowDatasetApi.inspect(uuids)
        pager.lists.map((item) => {
            const index = lists.findIndex((item1: any) => item.id === item1.id)
            if (index >= 0) {
                item.status = lists[index].status
                item.error = lists[index].error
                item.use_points = lists[index].use_points
                item.use_tokens = lists[index].use_tokens
                item.update_time = lists[index].update_time
            }
        })
    }
}

const { start, end } = usePolling(checkWaitingData, {
    time: 5000,
    key: 'dataset'
})

/**
 * 修正弹窗
 *
 * @param {string} uuid
 * @author zero
 */
const handleCorrect = (uuid: string) => {
    editShow.value = true
    editUuid.value = uuid
}

/**
 * 更新数据
 *
 * @param {any} data
 * @author zero
 */
const handleUpdate = async (data: any) => {
    if (!data.question) {
        return feedback.msgError('文档内容不能为空')
    }

    loading.value = true
    editShow.value = false
    if (data.uuid) {
        await knowDatasetApi.update({
            uuid: data.uuid,
            question: data.question,
            answer: data.answer,
            annex: data.annex
        }).finally(() => {
            loading.value = false
        })
        feedback.msgSuccess('修正成功')
    } else {
        await knowDatasetApi.insert({
            fid: props.archiveId,
            question: data.question,
            answer: data.answer,
            annex: data.annex
        }).finally(() => {
            loading.value = false
        })
        feedback.msgSuccess('插入成功')
    }

    await resetPaging()

    end()
    start()
}

/**
 * 重新训练
 *
 * @param {string[]} uuids
 * @author zero
 */
const handleRetry = async (uuids: string[]) => {
    await feedback.confirm('确定要重新学习吗?')
        .then(async () => {
            await knowDatasetApi.retry(props.know.code, uuids)
            await resetPaging()
            feedback.msgSuccess('发起成功')
        })

    end()
    start()
}

/**
 * 删除数据
 *
 * @param {string[]} uuids
 * @author zero
 */
const handleDelete = async (uuids: string[]) => {
    await feedback.confirm('确定要删除该数据吗?')
        .then(async () => {
            await knowDatasetApi.delete(props.know.code, uuids)
            await resetPaging()
            feedback.msgSuccess('删除成功')
        })

    end()
    start()
}

/**
 * 批量删除
 *
 * @author zero
 */
const batchDelete = async () => {
    const uuids = tableRef.value?.getSelectionRows().map((item: any) => item.id)
    if (!uuids || uuids.length <= 0) {
        return feedback.msgError('请选择要删除的数据')
    }
    await feedback.confirm('确定批量删除数据吗?')
        .then(async () => {
            await knowDatasetApi.delete(props.know.code, uuids || [])
            await resetPaging()
            feedback.msgSuccess('删除成功')
        })

    end()
    start()
}

/**
 * 批量重试
 *
 * @author zero
 */
const batchRetry = async () => {
    const uuids = tableRef.value?.getSelectionRows().map((item: any) => item.id)
    if (!uuids || uuids.length <= 0) {
        return feedback.msgError('请选择要重试的数据')
    }
    await feedback.confirm('确定批量重试学习吗?')
        .then(async () => {
            await knowDatasetApi.retry(props.know.code, uuids || [])
            await resetPaging()
            feedback.msgSuccess('操作成功')
        })

    end()
    start()
}

onMounted(async () => {
    archive.value = await knowArchiveApi.detail(props.archiveId)
    await queryLists()
    start()
})

onUnmounted(() => {
    end()
})
</script>
